/**
  * @File    :   main.c
  * @Time    :   2020/05/10 21:36:42
  * @Author  :   huenrong
  */

#include <stdio.h>
#include <stdint.h>

#include "./sx1276/sx1276_app.h"
#include "./icm20608/icm20608.h"

int main(int argc, char *argv[])
{
#if 0
    // sx1276测试代码
    sx1276_init(1);

    uint8_t version = -1;
    sx1276_read_version(&version);

    printf("sx1276 version: 0x%02X\n", version);

    return 0;
#endif

    // icm20608测试代码
    int ret = -1;
    int fd = -1;

    // icm20608初始化
    fd = icm20608_init();
    if (-1 == fd)
    {
        perror("icm20608 init fail");

        return -1;
    }

    // icm20608读取设备id
    uint8_t icm20608_id = 0;
    ret = icm20608_read_id(&icm20608_id, fd);
    if (0 != ret)
    {
        printf("icm20608 read id fail\n");
    }

    printf("icm20608 id: 0x%02X\n", icm20608_id);

    while (1)
    {
        // icm20608读取加速度值
        short read_accel_x = 0;
        short read_accel_y = 0;
        short read_accel_z = 0;
        ret = icm20608_read_accel(&read_accel_x, &read_accel_y, &read_accel_z, fd);
        if (0 != ret)
        {
            printf("icm20608 read accel fail\n");
        }

        // icm20608读取温度值
        short read_temp = 0;
        ret = icm20608_read_temp(&read_temp, fd);
        if (0 != ret)
        {
            printf("icm20608 read temp fail\n");
        }

        // icm20608读取陀螺仪值
        short read_gyro_x = 0;
        short read_gyro_y = 0;
        short read_gyro_z = 0;
        ret = icm20608_read_gyro(&read_gyro_x, &read_gyro_y, &read_gyro_z, fd);
        if (0 != ret)
        {
            printf("icm20608 read gyro fail\n");
        }

        // 计算各参数实际值
        float accel_x = (float)(read_accel_x / 2048);
        float accel_y = (float)(read_accel_y / 2048);
        float accel_z = (float)(read_accel_z / 2048);
        float gyro_x = (float)(read_gyro_x / 16.4);
        float gyro_y = (float)(read_gyro_y / 16.4);
        float gyro_z = (float)(read_gyro_z / 16.4);
        float temp = (float)(((read_temp - 25) / 326.8) + 25);

        // 打印各参数
        printf("accel_x = %.2f (g), accel_x = %.2f (g), accel_x = %.2f (g)\n", accel_x, accel_y, accel_z);
        printf("gyro_x = %.2f (°/S), gyro_x = %.2f (°/S), gyro_x = %.2f (°/S)\n", gyro_x, gyro_y, gyro_z);
        printf("temp = %.2f (°C)\n\n", temp);

        sleep(2);
    }

    icm20608_close(fd);

    return 0;
}
